package com.xcjw.com.Utils;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.text.TextUtils;

import com.xcjw.com.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;

/**
 * 
 * @ClassName: com.adwl.shippers.tools.FileUtils
 * @Description: 文件工具类
 * @author 马广驰
 * @date 2015-7-9 下午21:22:40
 * 
 */
public class FileUtils {
	/** 缓存文件目录 */
	private File mCacheDir;
	
	public FileUtils(Context context, String cacheDir) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED))
			mCacheDir = new File(cacheDir);
		else
			mCacheDir = context.getCacheDir();// 如何获取系统内置的缓存存储路径
		if (!mCacheDir.exists())
			mCacheDir.mkdirs();
	}

	public String getCacheDir() {
		return mCacheDir.getAbsolutePath();
	}
	
	/**
	 * @function 将一个对象保存到本地
	 * 
	 * @author D-light
	 * 
	 * @time 2014-07-23
	 *            name
	 * 
	 * @return void
	 */
	public static void saveObject(Context activity, String fileName,
								  Object object) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = activity.openFileOutput(fileName, Context.MODE_PRIVATE);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(object);
		} catch (Exception e) {
			e.printStackTrace();
			// 这里是保存文件产生异常
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					// fos流关闭异常
					e.printStackTrace();
				}
			}
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					// oos流关闭异常
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * @function 从本地读取保存的对象
	 * @author D-light
	 * @time 2014-07-23
	 *            name
	 * @return Object
	 */
	public static Object getObject(Context activity, String fileName) {

		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = activity.openFileInput(fileName);
			ois = new ObjectInputStream(fis);
			return ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
			// 这里是读取文件产生异常
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					// fis流关闭异常
					e.printStackTrace();
				}
			}
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					// ois流关闭异常
					e.printStackTrace();
				}
			}
		}
		// 读取产生异常，返回null
		return null;
	}
	
	 // 获取文件扩展名
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return "";
    }
    /**  
     * 解决小米手机上获取图片路径为null的情况  
     * @param intent  
     * @return  
     */  
     public static Uri geturi(Intent intent,Context context) {    
            Uri uri = intent.getData();    
            String type = intent.getType();    
            if (uri.getScheme().equals("file") && (type.contains("image/"))) {    
                String path = uri.getEncodedPath();    
                if (path != null) {    
                    path = Uri.decode(path);    
                    ContentResolver cr = context.getContentResolver();    
                    StringBuffer buff = new StringBuffer();    
                    buff.append("(").append(Images.ImageColumns.DATA).append("=")    
                            .append("'" + path + "'").append(")");    
                    Cursor cur = cr.query(Images.Media.EXTERNAL_CONTENT_URI,    
                            new String[] { Images.ImageColumns._ID },    
                            buff.toString(), null, null);    
                    int index = 0;    
                    for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {    
                        index = cur.getColumnIndex(Images.ImageColumns._ID);    
                        // set _id value    
                        index = cur.getInt(index);    
                    }    
                    if (index == 0) {    
                        // do nothing    
                    } else {    
                        Uri uri_temp = Uri    
                                .parse("content://media/external/images/media/"    
                                        + index);    
                        if (uri_temp != null) {    
                            uri = uri_temp;    
                        }    
                    }    
                }    
            }    
            return uri;    
        }
	/**
	 *
	 * @param
	 * @return
	 */
//	public static String getMD5FileDir(String root, String fileName) {
//		// FileAccessor.IMESSAGE_IMAGE + File.separator +
//		// FileAccessor.getSecondLevelDirectory(fileNameMD5)+ File.separator;
//		if (TextUtils.isEmpty(root)) {
//			return null;
//		}
//		File file = new File(root);
//		if (!file.exists()) {
//			file.mkdirs();
//		}
//
//		File fullPath = new File(file,
//				FileAccessor.getSecondLevelDirectory(fileName));
//		if (!fullPath.exists()) {
//			fullPath.mkdirs();
//		}
//		return fullPath.getAbsolutePath();
//	}

	@SuppressLint("NewApi")
	public static Bitmap createVideoThumbnail(String filePath) {
		Bitmap bitmap = null;
		MediaMetadataRetriever retriever = new MediaMetadataRetriever();
		try {
			// retriever.setMode(MediaMetadataRetriever.);
			retriever.setDataSource(filePath);

			bitmap = retriever.getFrameAtTime(1000);

		} catch (Exception ex) {

		} finally {
			try {
				retriever.release();

			} catch (RuntimeException ex) {
			}

		}
		return bitmap;

	}

	/**
	 * 转换成单位
	 *
	 * @param length
	 * @return
	 */
	public static String formatFileLength(long length) {
		if (length >> 30 > 0L) {
			float sizeGb = Math.round(10.0F * (float) length / 1.073742E+009F) / 10.0F;
			return sizeGb + " GB";
		}
		if (length >> 20 > 0L) {
			return formatSizeMb(length);
		}
		if (length >> 9 > 0L) {
			float sizekb = Math.round(10.0F * (float) length / 1024.0F) / 10.0F;
			return sizekb + " KB";
		}
		return length + " B";
	}

	/**
	 * 转换成Mb单位
	 *
	 * @param length
	 * @return
	 */
	public static String formatSizeMb(long length) {
		float mbSize = Math.round(10.0F * (float) length / 1048576.0F) / 10.0F;
		return mbSize + " MB";
	}

	/**
	 * 检查SDCARD是否可写
	 *
	 * @return
	 */
	public static boolean checkExternalStorageCanWrite() {
		try {
			boolean mouted = Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED);
			if (mouted) {
				boolean canWrite = new File(Environment
						.getExternalStorageDirectory().getAbsolutePath())
						.canWrite();
				if (canWrite) {
					return true;
				}
			}
		} catch (Exception e) {
		}
		return false;
	}

	/**
	 * 返回文件的图标
	 *
	 * @param fileName
	 * @return
	 */
	public static int getFileIcon(String fileName) {
		String fileType = fileName.toLowerCase();
		if (isDocument(fileType)) {
			return R.drawable.file_attach_doc;
		}
		if (isPic(fileType)) {
			return R.drawable.file_attach_img;
		}

		if (isCompresseFile(fileType)) {
			return R.drawable.file_attach_rar;
		}
		if (isTextFile(fileType)) {
			return R.drawable.file_attach_txt;
		}
		if (isPdf(fileType)) {
			return R.drawable.file_attach_pdf;
		}

		if (isPPt(fileType)) {
			return R.drawable.file_attach_ppt;
		}

		if (isXls(fileType)) {
			return R.drawable.file_attach_xls;
		}
		return R.drawable.file_attach_ohter;
	}

	/**
	 * 是否图片
	 *
	 * @param fileName
	 * @return
	 */
	public static boolean isPic(String fileName) {
		String lowerCase = DemoUtils.nullAsNil(fileName).toLowerCase();
		return lowerCase.endsWith(".bmp") || lowerCase.endsWith(".png")
				|| lowerCase.endsWith(".jpg") || lowerCase.endsWith(".jpeg")
				|| lowerCase.endsWith(".gif");
	}

	/**
	 * 是否压缩文件
	 *
	 * @param fileName
	 * @return
	 */
	public static boolean isCompresseFile(String fileName) {
		String lowerCase = DemoUtils.nullAsNil(fileName).toLowerCase();
		return lowerCase.endsWith(".rar") || lowerCase.endsWith(".zip")
				|| lowerCase.endsWith(".7z") || lowerCase.endsWith("tar")
				|| lowerCase.endsWith(".iso");
	}

	/**
	 * 是否音频
	 *
	 * @param fileName
	 * @return
	 */
	public static boolean isAudio(String fileName) {
		String lowerCase = DemoUtils.nullAsNil(fileName).toLowerCase();
		return lowerCase.endsWith(".mp3") || lowerCase.endsWith(".wma")
				|| lowerCase.endsWith(".mp4") || lowerCase.endsWith(".rm");
	}

	/**
	 * 是否文档
	 *
	 * @param fileName
	 * @return
	 */
	public static boolean isDocument(String fileName) {
		String lowerCase = DemoUtils.nullAsNil(fileName).toLowerCase();
		return lowerCase.endsWith(".doc") || lowerCase.endsWith(".docx")
				|| lowerCase.endsWith("wps");
	}

	/**
	 * 是否Pdf
	 *
	 * @param fileName
	 * @return
	 */
	public static boolean isPdf(String fileName) {
		return DemoUtils.nullAsNil(fileName).toLowerCase().endsWith(".pdf");
	}

	/**
	 * 是否Excel
	 *
	 * @param fileName
	 * @return
	 */
	public static boolean isXls(String fileName) {
		String lowerCase = DemoUtils.nullAsNil(fileName).toLowerCase();
		return lowerCase.endsWith(".xls") || lowerCase.endsWith(".xlsx");
	}

	/**
	 * 是否文本文档
	 *
	 * @param fileName
	 * @return
	 */
	public static boolean isTextFile(String fileName) {
		String lowerCase = DemoUtils.nullAsNil(fileName).toLowerCase();
		return lowerCase.endsWith(".txt") || lowerCase.endsWith(".rtf");
	}

	/**
	 * 是否Ppt
	 *
	 * @param fileName
	 * @return
	 */
	public static boolean isPPt(String fileName) {
		String lowerCase = DemoUtils.nullAsNil(fileName).toLowerCase();
		return lowerCase.endsWith(".ppt") || lowerCase.endsWith(".pptx");
	}

	/**
	 * decode file length
	 *
	 * @param filePath
	 * @return
	 */
	public static int decodeFileLength(String filePath) {
		if (TextUtils.isEmpty(filePath)) {
			return 0;
		}
		File file = new File(filePath);
		if (!file.exists()) {
			return 0;
		}
		return (int) file.length();
	}

	/**
	 * Gets the extension of a file name, like ".png" or ".jpg".
	 *
	 * @param uri
	 * @return Extension including the dot("."); "" if there is no extension;
	 *         null if uri was null.
	 */
	public static String getExtension(String uri) {
		if (uri == null) {
			return null;
		}

		int dot = uri.lastIndexOf(".");
		if (dot >= 0) {
			return uri.substring(dot);
		} else {
			// No extension.
			return "";
		}
	}

	/**
	 *
	 * @param filePath
	 * @return
	 */
	public static boolean checkFile(String filePath) {
		if (TextUtils.isEmpty(filePath) || !(new File(filePath).exists())) {
			return false;
		}
		return true;
	}

	/**
	 *
	 * @param filePath
	 * @param seek
	 * @param length
	 * @return
	 */
	public static byte[] readFlieToByte(String filePath, int seek, int length) {
		if (TextUtils.isEmpty(filePath)) {
			return null;
		}
		File file = new File(filePath);
		if (!file.exists()) {
			return null;
		}
		if (length == -1) {
			length = (int) file.length();
		}

		try {
			RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
			byte[] bs = new byte[length];
			randomAccessFile.seek(seek);
			randomAccessFile.readFully(bs);
			randomAccessFile.close();
			return bs;
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e("tab",e.toString());
			return null;
		}
	}

	public static int copyFile(File src, String filename, byte[] buffer) {
		if (!src.exists()) {
			return -1;
		}
		return copyFile(src.getAbsolutePath(), filename, buffer);
	}

	/**
	 * 拷贝文件
	 *
	 * @param fileDir
	 * @param fileName
	 * @param buffer
	 * @return
	 */
	public static int copyFile(String fileDir, String fileName, byte[] buffer) {
		if (buffer == null) {
			return -2;
		}

		try {
			File file = new File(fileDir);
			if (!file.exists()) {
				file.mkdirs();
			}
			File resultFile = new File(file, fileName);
			if (!resultFile.exists()) {
				resultFile.createNewFile();
			}
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
					new FileOutputStream(resultFile, true));
			bufferedOutputStream.write(buffer);
			bufferedOutputStream.flush();
			bufferedOutputStream.close();
			return 0;

		} catch (Exception e) {
		}
		return -1;
	}

	/**
	 * 根据文件名和后缀 拷贝文件
	 *
	 * @param fileDir
	 * @param fileName
	 * @param ext
	 * @param buffer
	 * @return
	 */
	public static int copyFile(String fileDir, String fileName, String ext,
							   byte[] buffer) {
		return copyFile(fileDir, fileName + ext, buffer);
	}

	/**
	 * 根据后缀名判断是否是图片文件
	 *
	 * @param type
	 * @return 是否是图片结果true or false
	 */
	public static boolean isImage(String type) {
		if (type != null
				&& (type.equals("jpg") || type.equals("gif")
				|| type.equals("png") || type.equals("jpeg")
				|| type.equals("bmp") || type.equals("wbmp")
				|| type.equals("ico") || type.equals("jpe"))) {
			return true;
		}
		return false;
	}

	public static String getFileExt(String fileName) {

		if (TextUtils.isEmpty(fileName)) {

			return "";
		}
		return fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length());
	}

	public static String getVideoMsgUrl(String url) {

		if (TextUtils.isEmpty(url)) {

			return "";
		}
		return url.substring(url.lastIndexOf("_") + 1,
				url.length());

	}
//	public static void refreshingMediaScanner(Context context , String pathName) {
//		if(TextUtils.isEmpty(pathName)) {
//			return ;
//		}
//		File dir = new File(FileAccessor.EXPORT_DIR , pathName);
//		// exportToGallery(context,dir.getAbsolutePath());
//		Uri uri = Uri.fromFile(dir);
//		Intent action = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE ,uri);
//		context.sendBroadcast(action);
//
//	}
}